"""
操作文档模型
"""
from sqlalchemy import Column, String, Text, Integer, ForeignKey, Float, Boolean
from sqlalchemy.orm import relationship
from .base import BaseModel


class OperationCategory(BaseModel):
    """操作分类模型"""
    __tablename__ = "operation_categories"
    
    name = Column(String(100), unique=True, nullable=False)
    description = Column(Text, nullable=True)
    parent_id = Column(Integer, ForeignKey("operation_categories.id"), nullable=True)
    sort_order = Column(Integer, default=0)
    
    # 自关联关系
    parent = relationship("OperationCategory", remote_side="OperationCategory.id", back_populates="children")
    children = relationship("OperationCategory", back_populates="parent")
    
    # 关联的操作文档
    operations = relationship("OperationDocument", back_populates="category")
    
    def __repr__(self):
        return f"<OperationCategory(name='{self.name}')>"


class OperationDocument(BaseModel):
    """操作文档模型"""
    __tablename__ = "operation_documents"
    
    title = Column(String(200), nullable=False)
    description = Column(Text, nullable=True)
    content = Column(Text, nullable=False)
    keywords = Column(Text, nullable=True)  # 逗号分隔的关键词
    platform = Column(String(50), nullable=True)  # Windows, Linux, macOS, etc.
    difficulty_level = Column(Integer, default=1)  # 1-5 难度等级
    risk_level = Column(Integer, default=1)  # 1-5 风险等级
    category_id = Column(Integer, ForeignKey("operation_categories.id"), nullable=True)
    is_active = Column(Boolean, default=True)
    view_count = Column(Integer, default=0)
    success_rate = Column(Float, default=0.0)  # 成功率统计
    
    # 向量嵌入相关
    embedding_id = Column(String(100), nullable=True)  # 在向量数据库中的ID
    
    # 关联关系
    category = relationship("OperationCategory", back_populates="operations")
    messages = relationship("ChatMessage", back_populates="operation")
    
    def __repr__(self):
        return f"<OperationDocument(title='{self.title}', platform='{self.platform}')>"
    
    @property
    def keyword_list(self):
        """获取关键词列表"""
        if self.keywords:
            return [kw.strip() for kw in self.keywords.split(",")]
        return []
    
    @keyword_list.setter
    def keyword_list(self, keywords):
        """设置关键词列表"""
        if isinstance(keywords, list):
            self.keywords = ",".join(keywords)
        else:
            self.keywords = keywords
